<?php
/*
 * @Author: 哲学家乔布斯 <wuyangii@qq.com>
 * @Date: 2022-10-20 22:33:03
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-10-20 23:32:31
 * @Descripttion: 
 */


namespace app\api\controller\user\v1_0;
use EasyWeChat\Factory;
use think\db\Where;

class Login extends Common
{
    protected $noNeedRight = ['aaaa'];
    /**
     * @Author: 哲学家乔布斯 <wuyangii@qq.com>
     * @brief: 
     * @return 
     * @Descripttion: 登入
     */    
    public function login($data, $type)
    {
        $model = new \app\common\model\User();
        $query = $model->where(1, 1);
        $user_id = 0; //保存用户id
        switch ($type) {
            case 'password':
                $info = $query->where(['username' => $data['mobile'], 'is_del' => 0])->field('id,password')->find();
                if (empty($info)) return self::errorResult('此用户不存在');
                if (StrMD5($data['password']) != $info['password']) return self::errorResult('您的密码错误');
                $user_id = $info['id'];
                break;
            case 'sms':
                $sms = (new \app\common\model\Sms())->where(['mobile' => $data['mobile'] , 'state' => 0])->order('id desc')->find();
                if(empty($sms['addtime'])){
                    return self::errorResult('验证码超时，请重新获取');
                }
                if (($sms['addtime'] + 600) < time()) {
                    return self::errorResult('验证码超时，请重新获取');
                }
                if($sms['code'] != $data['code']){
                    return self::errorResult('验证码错误');
                }
                // if (md5($data['mobile'] . $data['code']) != $data['codestr']) {
                //     return self::errorResult('验证码错误');
                // }
                $info = $query->where(['username' => $data['mobile'], 'is_del' => 0])->field('id')->find();
                if (empty($info)) {
                    //用户注册
                    $model->allowField(true)->save(['username' => $data['mobile'], 'name' => '用户' . rand(10000, 99999)]);
                    $user_id = $model->id;
                } else {
                    $user_id = $info['id'];
                }
                (new \app\common\model\Sms())->where(['mobile' => $data['mobile'] , 'state' => 0 ,'code' => $data['code']])->update(['state' => 1]);
                break;
            case 'mobile':
                $user_id = $query->where(['account' => $data['mobile'], 'is_del' => 0])->value('id');
                if (empty($user_id)) {
                    //用户注册
                    $model->allowField(true)->save(['account' => $data['mobile'], 'name' => '用户' . rand(10000, 99999)]);
                    $user_id = $model->id;
                }
                break;
            case 'wx':

                $user_id = $query->where(['openid' => $data['openid'], 'is_del' => 0])->value('id');
                if (empty($user_id)) {
                    //用户注册
                    $model->allowField(true)->save([
                                'openid' => $data['openid'],
                                'nickname' => empty(request()->param('nickname')) ? '用户'.rand(10000, 99999) : request()->param('nickname'),
                                'avatar' => empty(request()->param('avatar')) ? '' : request()->param('avatar'),
                                'agent_id' => $this->agent_id
                                ]);
                    $user_id = $model->id;
                }
                break;
            default:
                return self::errorResult('未知登录方式');
        }
        if(!empty($data['acid']) && !empty($data['app_source']) && $data['app_source']!="applet"){
            $model->where(['account' => $data['mobile'], 'is_del' => 0])->update(['acid' => $data['acid'], 'app_source' => $data['app_source']]);
        }
        $token = $model->setToken($user_id);
        if(!empty($token)){
            $user = (new \app\common\model\User())
                        ->where(['id' => $user_id])
                        ->append(['is_mobile'])
                        ->field(['id','nickname','username','avatar','token','mobile'])
                        ->withAttr("is_mobile",function($value,$data){
                            if($data['mobile']){
                                return 0;
                            }else{
                                return 1;
                            }
                        })
                        ->find();
        }
        // (new \app\common\model\LogApp())->save([
        //     'user_id' => $user_id,
        //     'type' => 'user',
        //     'username' => $user['username'],
        // ]);
        return empty($token) ? self::errorResult('登录失败') : self::successResult("成功",$user);
    }
        /**
     * 账号（手机号）+密码登录
     *
     * @return void
     */
    public function password()
    {
        $data = request()->param();
        $validate = new \app\common\validate\User();
        $result = $validate->scene('mobile_password_login')->check($data);
        if (!$result) {
            return self::errorResult($validate->getError());
        }
        return $this->login($data, 'password');
    }
    /**
     * 验证码登录
     *
     * @return void
     */
    public function sms()
    {
        $data = request()->param();
        $validate = new \app\common\validate\User();
        $result = $validate->scene('sms_login')->check($data);
        if (!$result) {
            return self::errorResult($validate->getError());
        }
        return $this->login($data, 'sms');
    }
    /**
     * 微信登录
     *
     * @return void
     */
    public function wechat(){
        $code = request()->param('code');
        $config = config('wechat.user.wechat');
     
        $app = Factory::miniProgram($config);
        $data = $app->auth->session($code);
    
        return $this->login($data, 'wx');
    }
    
    public function sample(){
        $mobile = request()->param('mobile');
        $sms = (new \app\common\model\Sms())->where(['mobile' => $mobile , 'state' => 0])->order('id desc')->find();
        if (!empty($sms) && ($sms['addtime'] + 60) > time()) {
            return self::errorResult('60秒内不能重复获取验证吗');
        }
        $data = (new \app\common\controller\Sample())->main($mobile);
        return self::successResult('成功');
    }
}
